package cn.com.aiouyi.service.impl;

import cn.com.aiouyi.entity.Accessory;
import cn.com.aiouyi.service.AccessoryService;
import cn.com.aiouyi.util.AssertUtils;
import cn.com.aiouyi.util.CommUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * Created by tommy on 2018/4/11.
 */
@Transactional
@Service(value = "accessoryServiceImpl")
public class AccessoryServiceImpl extends BaseServiceImpl<Accessory, Long> implements AccessoryService {
    @Resource
    private HttpServletRequest fetchedRequest;

    @Override
    public void delete(Long id) {
        AssertUtils.notNull(id);
        Accessory accessory = this.find(id);
        if (accessory != null) {

            String realPath = accessory.getPath();
            File destFile = new File(fetchedRequest.getServletContext().getRealPath(realPath));

            if (destFile.exists()) {
                try {
                    FileUtils.forceDelete(destFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            super.realDelete(accessory);
        }
    }

    @Override
    public void delete(Accessory accessory) {
        AssertUtils.notNull(accessory);

        String realPath = accessory.getPath();
        File destFile = new File(fetchedRequest.getServletContext().getRealPath(realPath));

        if (destFile.exists()) {
            try {
                FileUtils.forceDelete(destFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.realDelete(accessory);
    }

    @Override
    public void delete(Long[] ids) {
        AssertUtils.notNull(ids);
        AssertUtils.isTrue(ids.length > 0);
        for (int i = 0; i < ids.length; i++) {
            this.delete(ids[i]);
        }
    }
}
